<template>
  <div class="content-box" v-loading="!dataLoaded">
    <div class="content">
      <div class="group">
        <div class="header">
          <el-input readonly v-model="dptName">
            <template #append>
              <el-button :icon="Search" @click="dialogVisible = true" />
            </template>
          </el-input>
        </div>
        <div class="table-box" v-loading="loading">
          <ProTable
            ref="proTable"
            title="持卡人列表"
            rowKey="empid"
            :columns="columns"
            :request-api="getTableList"
            :data-callback="dataCallback"
            :tool-button="false"
            :select="_select"
            :click-row="_clickRow"
            :all-select-disabled="true"
            :search-col="{ xs: 1, sm: 1, md: 1, lg: 2, xl: 2 }"
            :small="true"
            v-if="zNodes.length && columns.length"
          >
            <template #tableHeader="scope">
              <el-button type="primary" text :icon="Open" @click="_openDoor(scope.selectedListIds)">远程开门</el-button>
            </template>
            <!-- Expand -->
            <template #expand="scope">
              {{ scope.row }}
            </template>
          </ProTable>
        </div>
      </div>
      <div class="main">
        <div class="table-box" v-loading="loading1">
          <el-tabs class="tabs" v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="门禁组" name="1">
              <RuleGroup class="tableItem" :empid="curEmployee?.empid" />
            </el-tab-pane>
            <el-tab-pane label="门禁点" name="2">
              <Door class="tableItem" :zNodes="zNodes" :empid="curEmployee?.empid" v-if="zNodes.length" />
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
    </div>
    <TreeDialog
      :zNodes="zNodes"
      :dialogVisible="dialogVisible"
      :handleClose="handleClose"
      :submitCallback="getOrgUnitIDs"
      v-if="zNodes.length"
    />
    <el-dialog v-model="dialogVisible2" title="远程开门" :before-close="handleClose">
      <el-form label-suffix=":">
        <el-form-item label="姓名">
          <el-input v-model="curEmployee.empname" readonly></el-input>
        </el-form-item>
        <el-form-item label="远程开门权限">
          <el-switch v-model="curEmployee.bopendoor"></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="tsx" name="cardholder">
import { onMounted, ref } from "vue";
import ProTable from "@/components/ProTable/index.vue";
import Door from "./components/Door.vue";
import RuleGroup from "./components/RuleGroup.vue";
import TreeDialog from "./components/TreeDialog.vue";
import { getEmployeeList } from "@/api/modules/cardIssuingCenter/employeeManage";

import { Search, Open } from "@element-plus/icons-vue";
import { getEmpcardTypes, saveOpenDoorRights } from "@/api/modules/elevatorControl/empower/cardholder";

import { getOrgTree } from "@/api/modules/common";
import { ElMessage, TabsPaneContext } from "element-plus";
const activeName = ref("1");
const dialogVisible = ref(false);
const dialogVisible1 = ref(false);
const dialogVisible2 = ref(false);
const dataLoaded = ref(false);
const loading = ref(false);
const loading1 = ref(false);
const proTable = ref();
const orgUnitIDs = ref([]);
const columns: any = ref([]);

const curEmployee: any = ref({});
const zNodes: any = ref([]);

const dptName = ref("");
const empcardTypes = ref([]);

const dataCallback = (data: any) => {
  const { records, page } = data;
  loading.value = false;
  return {
    list: records || [],
    total: page.total
  };
};

const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  loading.value = true;
  return getEmployeeList({ ...newParams, orgUnitIDs: orgUnitIDs.value });
};

/**
 * 多选框选择
 */
const _select = (selection, row) => {
  const selectedList = proTable.value.element.getSelectionRows();
  const isSel = selectedList.some(item => item.empid === row.empid);
  const lastSelItem = selection.shift();
  if (selection.length) {
    proTable.value.element.toggleRowSelection(lastSelItem, false);
  }
  curEmployee.value = isSel ? row : {};
};

/**
 * 单击行
 */
const _clickRow = row => {
  console.log(row);
  const selectedList = proTable.value.element.getSelectionRows();
  const isSel = selectedList.some(item => item.empid === row.empid);
  proTable.value.clearSelection();
  proTable.value.element.toggleRowSelection(row, isSel ? false : true);
  curEmployee.value = !isSel ? row : {};
};

const _openDoor = selectedListIds => {
  if (!selectedListIds.length) {
    ElMessage.error("请选择要远程开门的人员");
    return false;
  }
  dialogVisible2.value = true;
};

/**
 * 获取组织机构ids
 */
const getOrgUnitIDs = (name, ids) => {
  dptName.value = name;
  orgUnitIDs.value = ids;
  dialogVisible.value = false;
  curEmployee.value = {};
  proTable.value.clearSelection();
  proTable.value.getTableList();
};

/**
 * 关闭弹窗
 */
const handleClose = () => {
  dialogVisible.value = false;
  dialogVisible1.value = false;
  dialogVisible2.value = false;
};

const handleSubmit = async () => {
  try {
    await saveOpenDoorRights({
      empid: curEmployee.value.empid,
      bopendoor: curEmployee.value.bopendoor
    });
    ElMessage.success("设置成功");
    dialogVisible2.value = false;
  } catch (error) {
    console.log(error);
  }
};

/**
 * 获取员工类型
 */

const getEmpcardTypesData = async () => {
  try {
    const res = await getEmpcardTypes();
    empcardTypes.value = res.data.map(item => {
      return {
        label: item.value,
        value: item.value
      };
    });
    columns.value = [
      { type: "selection", fixed: "left", width: 60 },
      {
        prop: "cardType",
        label: "类型",
        isShow: false,
        enum: empcardTypes,
        search: { el: "select" }
      },
      {
        prop: "clause",
        label: "姓名",
        isShow: false,
        search: { el: "input" }
      },
      {
        prop: "empcode",
        label: "编号",
        minWidth: 200
      },
      {
        prop: "empname",
        label: "姓名",
        minWidth: 200
      },

      {
        prop: "cardType",
        label: "部门",
        minWidth: 200
      },
      {
        prop: "bopendoor",
        label: "远程开门",
        render: scope => {
          return (
            <>
              <el-checkbox disabled v-model={scope.row.bopendoor}></el-checkbox>
            </>
          );
        },
        minWidth: 120
      }
    ];
  } catch (error) {
    columns.value = [
      { type: "selection", fixed: "left", width: 60 },
      {
        prop: "clause",
        label: "姓名",
        isShow: false,
        search: { el: "input" }
      },
      {
        prop: "empcode",
        label: "编号",
        minWidth: 120
      },
      {
        prop: "empname",
        label: "姓名",
        minWidth: 120
      },

      {
        prop: "cardType",
        label: "部门",
        minWidth: 120
      },
      {
        prop: "bopendoor",
        label: "远程开门",
        render: scope => {
          return (
            <>
              <el-checkbox disabled v-model={scope.row.bopendoor}></el-checkbox>
            </>
          );
        },
        minWidth: 120
      }
    ];
    console.log(error);
  }
};

const getObjectData = async () => {
  try {
    const res = await getOrgTree();
    zNodes.value = res.data;
    if (zNodes.value.length) {
      dptName.value = zNodes.value[0].name;
      orgUnitIDs.value = getFlatMapData(zNodes.value).map(item => item.id);
    }
  } catch (error) {
    console.log(error);
  }
};

const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(tab, event);
};

/**
 * 展开树
 */
const getFlatMapData = (list: any) => {
  let newList = JSON.parse(JSON.stringify(list));
  return newList.flatMap((item: any) => [item, ...(item.children ? getFlatMapData(item.children) : [])]);
};

onMounted(async () => {
  Promise.all([getObjectData(), getEmpcardTypesData()]).then(() => {
    dataLoaded.value = true;
  });
});
</script>
<style scoped lang="scss">
@import "./index.scss";
</style>
